﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using OpenFileTransfer.Wpf.Models;
using OpenFileTransfer.Wpf.Services;
using Prism.Mvvm;

namespace OpenFileTransfer.Wpf.ViewModels
{
    internal class MainViewModel : BindableBase
    {
        public ObservableCollection<DeviceInfoDto> DeviceInfoList { get; }

        private readonly ICommunicationService _communicationService;

        public MainViewModel(ICommunicationService communicationService)
        {
            _communicationService = communicationService;

            DeviceInfoList = new ObservableCollection<DeviceInfoDto>();
            communicationService.UdpDeviceList.ForEach(t =>
            {
                DeviceInfoList.Add(new DeviceInfoDto()
                {
                    Id = t.DeviceId,
                    DisplayName = t.DisplayName,
                    RemarkName = t.DisplayName,
                    IsSelf = 0,
                    Online = true,
                    CreateTime = t.UpdateTime,
                    UpdateTime = t.UpdateTime
                });
            });

            communicationService.DeviceChanged += OnDeviceChanged;
        }

        private void OnDeviceChanged()
        {
            Application.Current?.Dispatcher.BeginInvoke(new Action(() =>
            {
                var items = DeviceInfoList
                    .Where(t => _communicationService.UdpDeviceList
                        .Any(device => device.DeviceId == t.Id))
                    .ToList();
                items.ForEach(t => { t.Online = true; });

                items = DeviceInfoList.Except(items).ToList();
                items.ForEach(t =>
                {
                    DeviceInfoList.Remove(t);
                    //t.Online = false;
                });

                var udpDeviceList = _communicationService.UdpDeviceList
                    .Where(t => DeviceInfoList.Any(info => info.Id == t.DeviceId))
                    .ToList();
                udpDeviceList = _communicationService.UdpDeviceList
                    .Except(udpDeviceList)
                    .ToList();
                udpDeviceList.ForEach(t => DeviceInfoList.Add(new DeviceInfoDto()
                {
                    Id = t.DeviceId,
                    DisplayName = t.DisplayName,
                    RemarkName = t.DisplayName,
                    IsSelf = 0,
                    Online = true,
                    CreateTime = t.UpdateTime,
                    UpdateTime = t.UpdateTime
                }));
            }), null);
        }
    }
}
